/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.FrameWork.Common;

import java.util.List;

import org.achartengine.ChartFactory;
import org.achartengine.chart.BarChart.Type;
import org.achartengine.renderer.XYMultipleSeriesRenderer;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.FragmentTransaction;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.RemoteViews;
import android.widget.TextView;

import com.FrameWork.Entity.CustomerInfoEntity;
import com.FrameWork.Entity.FunctionEntity;
import com.FrameWork.Entity.GlobalInfo;
import com.FrameWork.Synchoronization.SynchLogicManager;
import com.SFA.R;
import com.SFA.Customer.CustomerManager;
import com.SFA.FirstPage.HomePageManager;

public class MainActivity extends AbstractBaseActivity implements ActionBar.TabListener {

	private static final int NOTIFICATION_DEFAULT = 1;
	private static final String ACTION_DIALOG = "com.example.android.hcgallery.action.DIALOG";
	public static final String MESSAGE_URL = "http://114.112.197.234/service_sales/MESSAGESERVICE.ASMX";

	private static boolean createMain = true;
	private int mThemeId = -1;   
	private com.SFA.FirstPage.HomePageNewsView main_news;
	private com.SFA.FirstPage.HomePageNewOrderView main_new_orders;
	private LinearLayout ll_graph;
	private CustomerInfoEntity entity =null;


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		if(savedInstanceState != null && savedInstanceState.getInt("theme", -1) != -1) {
			mThemeId = savedInstanceState.getInt("theme");
			this.setTheme(mThemeId);
		}

		setContentView(R.layout.main);
		main_news = (com.SFA.FirstPage.HomePageNewsView)findViewById(R.id.main_news);
		main_new_orders = (com.SFA.FirstPage.HomePageNewOrderView)findViewById(R.id.main_new_orders);
		main_news.setTvTitle("最新消息");
		main_news.setTvMore("更多");
		main_new_orders.setTvTitle("今日订单");
		main_new_orders.setTvMore("更多");
		ll_graph = (LinearLayout)findViewById(R.id.ll_graph);
		XYMultipleSeriesRenderer renderer = HomePageManager.getBarDemoRenderer();
		View view = ChartFactory.getBarChartView(this, HomePageManager.getBarDemoDataset(), renderer, Type.DEFAULT);
		ll_graph.addView(view);
		ActionBar bar = getActionBar();
		bar.setTitle(GlobalInfo.GetInstance(context).getName());
		createMain = false;
		bar.hide();
		List<FunctionEntity> list = GlobalInfo.GetFunctionList();
		for (int i = 0; i < list.size(); i++) { 
			Tab tab = bar.newTab().setText(list.get(i).Title)
					.setTabListener(this);
			tab.setTag(list.get(i));

			bar.addTab(tab);
		}
		Tab tab = bar.newTab().setText("注销")
				.setTabListener(this);
		FunctionEntity entity = new FunctionEntity();
		entity.CODE="UNREGISTER";
		tab.setTag(entity);

		bar.addTab(tab);

		bar.selectTab(null);

		bar.show();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		new Thread(runnable).start();
		super.onResume();
	}

	private void newOrderInit(){
		/*newOrderList = HomePageManager.getOrderList(this);
		NewOrderAdapter newOrderAdapter = new NewOrderAdapter(this, newOrderList);
		main_new_orders.setLvNewOrder(newOrderAdapter);*/
	}

	private void newsInit(){
		/*newsList = HomePageManager.getMessageList(MESSAGE_URL, this);
		NewsAdapter newsAdapter = new NewsAdapter(this, newsList);
		main_news.setLvNewOrder(newsAdapter);*/
	}

	private Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);   
			switch(msg.what){
			case 0:
				newOrderInit();
				break;
			case 1:
				newsInit();
				break;
			}
		}

	};

	private Runnable runnable = new Runnable(){

		@Override
		public void run() {
			// TODO Auto-generated method stub
			/*newOrderList = HomePageManager.getOrderList(MainActivity.this);
			handler.sendEmptyMessage(0);
			newsList = HomePageManager.getMessageList(MESSAGE_URL, MainActivity.this);
			handler.sendEmptyMessage(1);*/
		}

	};

	// 返回键监听
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		//
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			// do something on back.

			Builder builder = new AlertDialog.Builder(this)
			.setIcon(android.R.drawable.ic_dialog_alert)
			.setTitle(R.string.MSG_002)
			.setPositiveButton(R.string.EXIT,
					new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog,
						int which) {

					MyApplication.getInstance().exit();
				}

			});

			if (MyApplication.getInstance().SyncMonitor != null)

				// 判断是否有未上传的数据，提示用户
				try {

					int count = new SynchLogicManager()
					.GetUnuploadDataCount(MyApplication.getInstance()
							.SyncMonitor.Process);
					if (count > 0) {
						builder.setTitle(R.string.MSG_005);
					}
				} catch (Exception err) {
					err.printStackTrace();
				}
			builder.setNegativeButton(R.string.CANCEL, null).show();

		}

		return super.onKeyDown(keyCode, event);
	}


	private boolean showBool = false;
	public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
		if(tab==null)
			return;
		ActionBar bar = getActionBar();
		if(!bar.isShowing())
			return;
		FunctionEntity functionEntity = (FunctionEntity) tab.getTag();

		Intent intent = null;
		Class c = null;
		if (functionEntity.CODE.equals("MESSAGE"))
		{
			c = com.SFA.Message.MessageListActivity.class;
		}
		else
			if (functionEntity.CODE.equals("SYNC"))
			{
				c =com.FrameWork.Synchoronization.SyncActivity.class;
			}


			else if (functionEntity.CODE.equals("ORDERMANAGEMENT"))
			{
				c = com.SFA.OrderManagement.OrderListActivity.class;
			}
			else if(functionEntity.CODE.equals("PRODUCTSHOW"))
			{
				showBool = true;
				c = com.SFA.ProductShow.ExploreProductActivity.class;

			}
			else if(functionEntity.CODE.equals("DOWNLOADPHOTO"))
			{
				try {
					c = Class.forName("com.SFA.DownLoadPhoto.ProductPhotoDownloadActivity");
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
			}
			else if (functionEntity.CODE.equals("UNREGISTER"))
			{
				Builder builder = new AlertDialog.Builder(this)
				.setIcon(android.R.drawable.ic_dialog_alert)
				.setTitle("你确定注销该账号吗")
				.setPositiveButton("注销",
						new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog,
							int which) {
						SharedPreferences preferencce = context.getSharedPreferences("login", Context.MODE_PRIVATE);
						Editor editor = preferencce.edit();
						editor.putBoolean("isAutomatic", false);
						editor.commit();
						MyApplication.getInstance().exit();
					}

				});

				if (MyApplication.getInstance().SyncMonitor != null)

					// 判断是否有未上传的数据，提示用户
					try {

						int count = new SynchLogicManager()
						.GetUnuploadDataCount(MyApplication.getInstance()
								.SyncMonitor.Process);
						if (count > 0) {
							builder.setTitle(R.string.MSG_005);
						}
					} catch (Exception err) {
						err.printStackTrace();
					}
				builder.setNegativeButton(R.string.CANCEL, null).show();
				return;
			}


			else if (functionEntity.CODE.equals("EXIT"))
			{
				Builder builder = new AlertDialog.Builder(this)
				.setIcon(android.R.drawable.ic_dialog_alert)
				.setTitle(R.string.MSG_002)
				.setPositiveButton(R.string.EXIT,
						new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog,
							int which) {

						MyApplication.getInstance().exit();
					}

				});

				if (MyApplication.getInstance().SyncMonitor != null)

					// 判断是否有未上传的数据，提示用户
					try {

						int count = new SynchLogicManager()
						.GetUnuploadDataCount(MyApplication.getInstance()
								.SyncMonitor.Process);
						if (count > 0) {
							builder.setTitle(R.string.MSG_005);
						}
					} catch (Exception err) {
						err.printStackTrace();
					}
				builder.setNegativeButton(R.string.CANCEL, null).show();
				return;
			}
			else
				if (functionEntity.CODE.equals("ABOUT"))
				{
					final Dialog dialog = new Dialog(this);
					dialog.setContentView(R.layout.about);
					dialog.getWindow().setWindowAnimations(R.style.dialogWindowAnim);
					dialog.show();

					TextView textView = (TextView) dialog.getWindow().findViewById(
							R.id.about_version);
					PackageManager packageManager = this.getPackageManager();
					PackageInfo packageInfo = null;
					try {
						packageInfo = packageManager.getPackageInfo(
								this.getPackageName(), 0);
					} catch (NameNotFoundException e) {
						e.printStackTrace();
					}
					textView.setText(packageInfo.versionName);
					dialog.getWindow().findViewById(R.id.about_but_back)
					.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							dialog.cancel();
						}
					});
					return;

				}
				else
					if (functionEntity.TYPE.equals("1"))
					{
						try
						{
							c = Class.forName("cofco.Mobile.UI.NewsListActivity");
						}
						catch (ClassNotFoundException e)
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					else
						if (functionEntity.TYPE.equals("4"))
						{
							c= com.SFA.Web.WebViewActivity.class;
						}

		if (c != null)
		{


			intent = new Intent(this, c);
			intent.putExtra("title", functionEntity.Title);// 标题
			intent.putExtra("RSS", functionEntity.RSS);// 获取RSSURL
			intent.putExtra("URL", functionEntity.URL);
			intent.putExtra("CODE", functionEntity.CODE);
			if(showBool){
				//查找客户资料
				List<CustomerInfoEntity> list = new CustomerManager(this).getCustomerList();
				if(list != null && list.size() >0)
					entity = list.get(0);

				intent.putExtra("CustomerInfo", entity);
			}
			startActivity(intent);
			overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
			bar.selectTab(null);
		}
	}



	public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
	}

	public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
	}





	void showNotification(boolean custom) {
		final Resources res = getResources();
		final NotificationManager notificationManager = (NotificationManager) getSystemService(
				NOTIFICATION_SERVICE);

		Notification.Builder builder = new Notification.Builder(this)
		.setSmallIcon(R.drawable.ic_stat_notify_example)
		.setAutoCancel(true)
		.setTicker("NOTIFICATION")
		.setContentIntent(getDialogPendingIntent("Tapped the notification entry."));

		if (custom) {
			RemoteViews layout = new RemoteViews(getPackageName(), R.layout.notification);
			layout.setTextViewText(R.id.notification_title, getString(R.string.app_name));
			layout.setOnClickPendingIntent(R.id.notification_button,
					getDialogPendingIntent("Tapped the 'dialog' button in the notification."));
			builder.setContent(layout);
			/*Bitmap largeIconTemp = BitmapFactory.decodeResource(res,
					R.drawable.notification_default_largeicon);
			Bitmap largeIcon = Bitmap.createScaledBitmap(
					largeIconTemp,
					res.getDimensionPixelSize(android.R.dimen.notification_large_icon_width),
					res.getDimensionPixelSize(android.R.dimen.notification_large_icon_height),
					false);
			largeIconTemp.recycle();

			builder.setLargeIcon(largeIcon);*/

		} else {
			builder
			.setNumber(7) // An example number.
			.setContentTitle(getString(R.string.app_name))
			.setContentText("notification_text");
		}

		notificationManager.notify(NOTIFICATION_DEFAULT, builder.getNotification());
	}

	PendingIntent getDialogPendingIntent(String dialogText) {
		return PendingIntent.getActivity(
				this,
				dialogText.hashCode(), // Otherwise previous PendingIntents with the same
				// requestCode may be overwritten.
				new Intent(ACTION_DIALOG)
				.putExtra(Intent.EXTRA_TEXT, dialogText)
				.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
				0);
	}

	@Override
	public void onSaveInstanceState (Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt("theme", mThemeId);
	}


}
